<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告提示框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cateFilter">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            clearable
            v-model="selectedValue"
            :options="selectedCate"
            :props="cateProps"
            @change="selectedValueChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisableBtn" @click="addParamsDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editTable(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteTable(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisableBtn" @click="addParamsDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editTable(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteTable(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/添加属性 对话框 -->
    <el-dialog :title="'添加' + isTabsName" :visible.sync="addParamsDialogVisible" width="50%" @close="addParamsDialogClosed">
      <el-form :model="addParamsForm" label-width="80px" ref="addParamsFormRef" :rules="addParamsFormRules">
        <el-form-item :label="isTabsName" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数 对话框 -->
    <el-dialog :title="'修改' + isTabsName" :visible.sync="editParamsDialogVisible" width="50%" @close="editParamsDialogClosed">
      <el-form :model="editParamsForm" label-width="80px" ref="editParamsFormRef" :rules="editParamsFormRules">
        <el-form-item :label="isTabsName" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      selectedCate: [],
      selectedValue: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 添加参数 对话框显隐
      addParamsDialogVisible: false,
      // 添加参数 对话框数据
      addParamsForm: {},
      // 添加参数 对话框校验
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 编辑 对话框 显隐
      editParamsDialogVisible: false,
      // 编辑 对话框数据
      editParamsForm: {},
      // 编辑 对话框表单校验
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  // 计算属性
  computed: {
    // 通过判断 下拉菜单选项的长度 返回true或false 让添加按钮显隐
    isDisableBtn() {
      if(this.selectedValue.length !== 3) {
        return true
      }
      return false
    },
    // 根据 下拉菜单选项的长度 返回数组中最后一个值 则为三级分类的id
    cateId() {
      if(this.selectedValue.length === 3) {
        return this.selectedValue[2]
      }
      return null
    },
    isTabsName() {
      if(this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.selectedCate = res.data
    },
    // 三级联动的选择改变 触发此函数
    selectedValueChange() {
      this.getParamsList()
    },
    // 获取参数数据
    async getParamsList() {
      if(this.selectedValue.length !== 3) {
        this.selectedValue = []
        // 动态参数的数据清空
        this.manyTableData = []
        // 静态属性的数据清空
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if(this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 切换 tabs 面板触发此函数
    handleTabsClick() {
      this.getParamsList()
    },
    // 点击编辑按钮
    async editTable(id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if(res.meta.status !== 200) return this.$message.error('查询参数失败')
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 修改参数
    editParams() {
      this.$refs.editParamsFormRef.validate(async valid => {
        if(!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 200) return this.$message.error('修改' + this.isTabsName + '失败')
        this.$message.success('修改' + this.isTabsName + '成功')
        this.editParamsDialogVisible = false
        this.getParamsList()
      })
    },
    // 删除参数
    deleteTable(attrId) {
      this.$msgbox.confirm('此操作将永久删除该' + this.isTabsName + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
        if(res.meta.status !== 200) return this.$message.error('删除' + this.isTabsName + '失败')
        this.$message.success('删除' + this.isTabsName + '成功!')
        this.getParamsList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 关闭添加参数对话框 重置表单
    addParamsDialogClosed() {
      this.$refs.addParamsFormRef.resetFields()
      // console.log(this.addParamsForm)
      this.addParamsForm = {}
    },
    editParamsDialogClosed() {
      this.$refs.editParamsFormRef.resetFields()
      // console.log(this.editParamsForm)
      this.editParamsForm = {}
    },
    // 添加参数/属性
    addParams() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if(!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 201) return this.$message.error('添加' + this.isTabsName + '失败')
        this.$message.success('添加' + this.isTabsName + '成功')
        this.addParamsDialogVisible = false
        this.getParamsList()
      })
    },
    // 文本框失去焦点 或 按下键盘Enter键
    handleInputConfirm(row) {
      if(row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 输入框不为空时
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.updateTag(row)
    },
    async updateTag(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status !== 200) return this.$message.error('更新参数失败')
      this.$message.success('更新参数成功')
    },
    // 点击新增加tag标签按钮
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.updateTag(row)
    }
  }
}
</script>
<style lang="less" scoped>
.cateFilter{
  margin: 15px 0;
}
.el-table{
  margin-top: 20px;
  font-size: 12px;
}
.el-tag{
  margin: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 120px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
